package partB;

import misc.not_Legal_Exception;
import evolution_superclasses.Phenotype;

public class B_Fitness_Evaluation{
	private double _refactor, _moraleLoss;

	public B_Fitness_Evaluation(int nr){
	}

	public double get_refactor() {
		return _refactor;
	}

	public void set_refactor(double refactor) {
		_refactor = refactor;
	}

	public double get_moraleLoss() {
		return _moraleLoss;
	}

	public void set_moraleLoss(double moraleLoss) {
		_moraleLoss = moraleLoss;
	}

	public void evaluateFitness(Phenotype[] p) throws not_Legal_Exception {
		for(int i = 0; i < p.length; i++){
			for(int j = i+1; j < p.length; j++){
				battle(p[i],p[j]);
			}
		}
	}
	
	private void battle(Phenotype p, Phenotype p2){
		B_Phenotype bp = (B_Phenotype) p;
		B_Phenotype bp2 = (B_Phenotype) p2;

		double[] strategy = bp.get_weights().clone();
		double[] strategy2 = bp2.get_weights().clone();

		double strength = 1;
		double strength2 = 1;
		double resources, resources2;
		
		int battleNumber = strategy.length;
		
		for(int i = 0; i < battleNumber; i++){
			resources = strategy[i]*strength;
			resources2 = strategy2[i]*strength2;
			
			if(resources > resources2){
				strength2 -= _moraleLoss;
				bp.win();
				redeploy(strategy, i+1, _refactor*(strategy[i]-strategy2[i]));
			}else if(resources < resources2){
				strength -= _moraleLoss;
				bp2.win();
				redeploy(strategy2, i+1, _refactor*(strategy2[i]-strategy[i]));
			}else{
				bp.tie();
				bp2.tie();
			}
		}
	}
	
	private void redeploy(double[] strategy, int begin, double resources){
		if(resources < 0)return; //They were stronger, yet there's not enough people to help
		double resourcePrBattle = resources/(strategy.length-begin);
		for(int i = begin; i < strategy.length; i++){
			strategy[i] += resourcePrBattle;
		}
	}

}
